package com.devframe.srtp.client.support;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
import org.jboss.netty.handler.codec.http.HttpChunk;
import org.jboss.netty.handler.codec.http.HttpResponse;
import org.jboss.netty.util.CharsetUtil;

import com.devframe.srtp.SRTPResult;
import com.devframe.srtp.util.common.SRTPJSONUtil;

public class SRTPClientHandler extends SimpleChannelUpstreamHandler {

    private static final Log logger =LogFactory.getLog(SRTPClientHandler.class);
    private boolean readingChunks;
    private final StringBuilder responseContent = new StringBuilder();
    
    private SRTPResult result;

    public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
        if (!readingChunks) {
            HttpResponse response = (HttpResponse) e.getMessage();
            logger.info("STATUS: " + response.getStatus());
            if (response.getStatus().getCode() == 200 && response.isChunked()) {
                readingChunks = true;
            } else {
                ChannelBuffer content = response.getContent();
                if (content.readable()) {
                   responseContent.append(content.toString(CharsetUtil.UTF_8));
                }
            }
        } else {
            HttpChunk chunk = (HttpChunk) e.getMessage();
            if (chunk.isLast()) {
                readingChunks = false;
                responseContent.append(chunk.getContent().toString(CharsetUtil.UTF_8));
//                logger.info(responseContent);
                String json=responseContent.toString();
                result=SRTPJSONUtil.parseObject(json, SRTPResult.class);
//                logger.info("msg:"+result.getMsg());
//                logger.info("filePath="+result.getFilePath());
            } else {
            	responseContent.append(chunk.getContent().toString(CharsetUtil.UTF_8));
            }
        }
    }
    public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)
            throws Exception {
        e.getCause().printStackTrace();
        e.getChannel().close();
    }
	public SRTPResult getResult() {
		return result;
	}
    
    
}
